const express = require('express')
const cors = require('cors')
const userRouter = require('./router/user')
const expressJwt = require('express-jwt')
const config = require('./config')
const R = require('./response')
const { ValidationError } = require("joi")
const columnRouter = require('./router/column')
const articleRouter = require('./router/article')

const app = express()
// 开启跨域
app.use(cors())
// 开启数据解析
app.use(express.json({ limit: '50MB' }))
app.use(express.urlencoded({ limit: '50MB', extended: true }))

// 配置身份认证中间件 登录和注册不需要认证
app.use(expressJwt({ secret: config.jwtSecretKey }).unless({ path: ['/api/user/login', '/api/users', '/api/list/columns']}))

app.use('/api', userRouter)
app.use('/api', columnRouter)
app.use('/api', articleRouter)

// 配置错误处理中间件
app.use((err, req, res, next) => {
    if (err instanceof ValidationError) {
        return res.send(new R(1, err.message))
    }
    if (err.name === 'UnauthorizedError') {
        return res.sendStatus(401)
    }
    return res.send(new R(1, err.message))
})

app.listen(3007, () => {
    console.log('zhzy server running at http://localhost:3007')
})